package com.dtborad.myblog.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> implements Serializable {
    private Boolean succ;
    private Long ts;
    private T data;
    private Integer code;
    private String msg;

    // 构造函数中自动生成时间戳
    public Result(Boolean succ, T data, Integer code, String msg) {
        this.succ = succ;
        this.ts = System.currentTimeMillis(); // 自动生成时间戳
        this.data = data;
        this.code = code;
        this.msg = msg;
    }

    public static <T> Result<T> ofSuccess() {
        return new Result<>(true, null, 200, null);
    }

    public static <T> Result<T> ofSuccess(T data) {
        return new Result<>(true, data, 200, null);
    }

    public static <T> Result<T> ofFail(String code, String msg) {
        return new Result<>(false, null, Integer.valueOf(code), msg);
    }

    public static <T> Result<T> ofFail(String code, String msg, T data) {
        return new Result<>(false, data, Integer.valueOf(code), msg);
    }

    public static <T> Result<T> ofFail(CommonErrorCode resultEnum) {
        return new Result<>(false, null, resultEnum.getCode(), resultEnum.getMessage());
    }

    public String buildResultJson(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success", this.succ);
        jsonObject.put("code", this.code);
        jsonObject.put("ts", this.ts);
        jsonObject.put("msg", this.msg);
        jsonObject.put("data", this.data);
        return JSON.toJSONString(jsonObject, SerializerFeature.DisableCircularReferenceDetect);
    }
}
